<?php

namespace app\common\service;

use Exception;
use extcore\upload\UploadInterface;

class UploadService extends BaseService
{
    /**
     * @var UploadInterface
     */
    protected static $driver;

    /**
     * @var UploadInterface
     */
    protected static $mirrorDriver;

    /**
     * 创建文件管理驱动
     * @return UploadInterface
     */
    private static function createDriver($isMirror = false)
    {
        $config = config('upload.');
        $driver = $isMirror ? $config['driver_mirror'] : $config['driver'];
        if (empty($driver)) return null;
        $uploadDriver = '\\extcore\\upload\\' . ucfirst($driver) . 'Driver';
        if (!class_exists($uploadDriver)) {
            return null;
        }
        return new $uploadDriver(config('upload.'));
    }

    /**
     * 获取默认驱动
     * @return UploadInterface
     */
    public static function getDriver()
    {
        if (static::$driver == null) {
            static::$driver = static::createDriver();
            if (!static::$driver) {
                throw new \Exception("Upload Driver not found", 500);
            }
        }
        return static::$driver;
    }

    /**
     * 获取镜像驱动
     * @param bool $orLocal 镜像驱动不存在时是否返回默认驱动
     * @return UploadInterface
     */
    public static function getMirrorDriver($orLocal = false)
    {
        if (static::$mirrorDriver == null) {
            static::$mirrorDriver = static::createDriver(true);
            if ($orLocal) return static::getDriver();
            if (!static::$mirrorDriver) {
                throw new \Exception("Upload Driver not found", 500);
            }
        }
        return static::$mirrorDriver;
    }

    /**
     * 生成缩略图
     * @param string $src 
     * @param string $argument 
     * @return string 
     * @throws Exception 
     */
    public static function thumb($src, $argument)
    {
        return static::getMirrorDriver(true)->thumb($src, $argument);
    }

    /**
     * 删除文件，同时尝试删除镜像文件
     * @param string|array $src 
     * @return bool 
     * @throws Exception 
     */
    public static function delete($src)
    {
        if (static::getDriver()->delFile($src)) {
            try {
                static::getMirrorDriver()->delFile($src);
            } catch (\Exception $e) {
            }

            return true;
        }
        return false;
    }
}
